package com.caseprocessing.config;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * 配置管理工具
 * 提供交互式配置管理功能
 */
public class ConfigurationTool {
    
    private final AIConfig config;
    private final Scanner scanner;
    
    public ConfigurationTool() {
        this.config = AIConfig.getInstance();
        this.scanner = new Scanner(System.in);
    }
    
    /**
     * 运行配置工具
     */
    public void run() {
        System.out.println("🔧 AI配置管理工具");
        System.out.println("=" .repeat(50));
        
        while (true) {
            printMenu();
            String choice = scanner.nextLine().trim();
            
            switch (choice) {
                case "1":
                    viewCurrentConfiguration();
                    break;
                case "2":
                    configureApiSettings();
                    break;
                case "3":
                    configureModelSettings();
                    break;
                case "4":
                    configureProcessingSettings();
                    break;
                case "5":
                    testConfiguration();
                    break;
                case "6":
                    exportConfiguration();
                    break;
                case "7":
                    resetToDefaults();
                    break;
                case "0":
                    System.out.println("👋 退出配置工具");
                    return;
                default:
                    System.out.println("❌ 无效选择，请重新输入");
            }
            
            System.out.println("\n按回车键继续...");
            scanner.nextLine();
        }
    }
    
    /**
     * 打印菜单
     */
    private void printMenu() {
        System.out.println("\n📋 配置管理菜单:");
        System.out.println("1. 查看当前配置");
        System.out.println("2. 配置API设置");
        System.out.println("3. 配置模型设置");
        System.out.println("4. 配置处理设置");
        System.out.println("5. 测试配置");
        System.out.println("6. 导出配置");
        System.out.println("7. 重置为默认值");
        System.out.println("0. 退出");
        System.out.print("请选择 (0-7): ");
    }
    
    /**
     * 查看当前配置
     */
    private void viewCurrentConfiguration() {
        System.out.println("\n📊 当前配置信息:");
        config.printConfiguration();
    }
    
    /**
     * 配置API设置
     */
    private void configureApiSettings() {
        System.out.println("\n🔧 配置API设置");
        System.out.println("-".repeat(30));
        
        // API密钥
        System.out.print("API密钥 [当前: " + maskApiKey(config.getApiKey()) + "]: ");
        String apiKey = scanner.nextLine().trim();
        if (!apiKey.isEmpty()) {
            config.setApiKey(apiKey);
            System.out.println("✅ API密钥已更新");
        }
        
        // API基础URL
        System.out.print("API基础URL [当前: " + config.getApiBaseUrl() + "]: ");
        String baseUrl = scanner.nextLine().trim();
        if (!baseUrl.isEmpty()) {
            config.setProperty("siliconflow.api.base.url", baseUrl);
            System.out.println("✅ API基础URL已更新");
        }
        
        // API超时时间
        System.out.print("API超时时间(毫秒) [当前: " + config.getApiTimeout() + "]: ");
        String timeout = scanner.nextLine().trim();
        if (!timeout.isEmpty()) {
            try {
                int timeoutMs = Integer.parseInt(timeout);
                config.setProperty("siliconflow.api.timeout", String.valueOf(timeoutMs));
                System.out.println("✅ API超时时间已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的超时时间格式");
            }
        }
        
        // API重试次数
        System.out.print("API重试次数 [当前: " + config.getApiRetryAttempts() + "]: ");
        String retries = scanner.nextLine().trim();
        if (!retries.isEmpty()) {
            try {
                int retryCount = Integer.parseInt(retries);
                config.setProperty("siliconflow.api.retry.attempts", String.valueOf(retryCount));
                System.out.println("✅ API重试次数已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的重试次数格式");
            }
        }
    }
    
    /**
     * 配置模型设置
     */
    private void configureModelSettings() {
        System.out.println("\n🤖 配置模型设置");
        System.out.println("-".repeat(30));
        
        // LLM模型
        System.out.print("LLM模型名称 [当前: " + config.getLlmModelName() + "]: ");
        String llmModel = scanner.nextLine().trim();
        if (!llmModel.isEmpty()) {
            config.setProperty("llm.model.name", llmModel);
            System.out.println("✅ LLM模型已更新");
        }
        
        // VLM模型
        System.out.print("VLM模型名称 [当前: " + config.getVlmModelName() + "]: ");
        String vlmModel = scanner.nextLine().trim();
        if (!vlmModel.isEmpty()) {
            config.setProperty("vlm.model.name", vlmModel);
            System.out.println("✅ VLM模型已更新");
        }
        
        // LLM最大Token数
        System.out.print("LLM最大Token数 [当前: " + config.getLlmMaxTokens() + "]: ");
        String llmTokens = scanner.nextLine().trim();
        if (!llmTokens.isEmpty()) {
            try {
                int tokens = Integer.parseInt(llmTokens);
                config.setProperty("llm.model.max.tokens", String.valueOf(tokens));
                System.out.println("✅ LLM最大Token数已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的Token数格式");
            }
        }
        
        // LLM温度参数
        System.out.print("LLM温度参数 [当前: " + config.getLlmTemperature() + "]: ");
        String llmTemp = scanner.nextLine().trim();
        if (!llmTemp.isEmpty()) {
            try {
                double temperature = Double.parseDouble(llmTemp);
                if (temperature >= 0 && temperature <= 2) {
                    config.setProperty("llm.model.temperature", String.valueOf(temperature));
                    System.out.println("✅ LLM温度参数已更新");
                } else {
                    System.out.println("❌ 温度参数必须在0-2之间");
                }
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的温度参数格式");
            }
        }
    }
    
    /**
     * 配置处理设置
     */
    private void configureProcessingSettings() {
        System.out.println("\n⚙️ 配置处理设置");
        System.out.println("-".repeat(30));
        
        // 批处理大小
        System.out.print("批处理大小 [当前: " + config.getBatchSize() + "]: ");
        String batchSize = scanner.nextLine().trim();
        if (!batchSize.isEmpty()) {
            try {
                int size = Integer.parseInt(batchSize);
                config.setProperty("processing.batch.size", String.valueOf(size));
                System.out.println("✅ 批处理大小已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的批处理大小格式");
            }
        }
        
        // 最大并发数
        System.out.print("最大并发数 [当前: " + config.getMaxConcurrency() + "]: ");
        String concurrency = scanner.nextLine().trim();
        if (!concurrency.isEmpty()) {
            try {
                int maxConcurrency = Integer.parseInt(concurrency);
                config.setProperty("processing.max.concurrency", String.valueOf(maxConcurrency));
                System.out.println("✅ 最大并发数已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的并发数格式");
            }
        }
        
        // 处理超时时间
        System.out.print("处理超时时间(秒) [当前: " + config.getProcessingTimeout() + "]: ");
        String timeout = scanner.nextLine().trim();
        if (!timeout.isEmpty()) {
            try {
                int timeoutSeconds = Integer.parseInt(timeout);
                config.setProperty("processing.timeout.seconds", String.valueOf(timeoutSeconds));
                System.out.println("✅ 处理超时时间已更新");
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的超时时间格式");
            }
        }
        
        // 质量置信度阈值
        System.out.print("质量置信度阈值 [当前: " + config.getQualityConfidenceThreshold() + "]: ");
        String threshold = scanner.nextLine().trim();
        if (!threshold.isEmpty()) {
            try {
                double confidenceThreshold = Double.parseDouble(threshold);
                if (confidenceThreshold >= 0 && confidenceThreshold <= 1) {
                    config.setProperty("quality.confidence.threshold", String.valueOf(confidenceThreshold));
                    System.out.println("✅ 质量置信度阈值已更新");
                } else {
                    System.out.println("❌ 置信度阈值必须在0-1之间");
                }
            } catch (NumberFormatException e) {
                System.out.println("❌ 无效的阈值格式");
            }
        }
    }
    
    /**
     * 测试配置
     */
    private void testConfiguration() {
        System.out.println("\n🧪 测试配置");
        System.out.println("-".repeat(30));
        
        System.out.println("正在验证配置...");
        boolean valid = config.validateConfiguration();
        
        if (valid) {
            System.out.println("✅ 配置验证通过！");
            
            // 可以添加更多测试，如API连接测试
            System.out.println("\n📋 配置总结:");
            System.out.println("- API基础URL: " + config.getApiBaseUrl());
            System.out.println("- LLM模型: " + config.getLlmModelName());
            System.out.println("- VLM模型: " + config.getVlmModelName());
            System.out.println("- 批处理大小: " + config.getBatchSize());
            System.out.println("- 最大并发数: " + config.getMaxConcurrency());
        } else {
            System.out.println("❌ 配置验证失败，请检查相关设置");
        }
    }
    
    /**
     * 导出配置
     */
    private void exportConfiguration() {
        System.out.println("\n📤 导出配置");
        System.out.println("-".repeat(30));
        
        System.out.print("导出文件路径 [默认: exported-ai-config.properties]: ");
        String filePath = scanner.nextLine().trim();
        if (filePath.isEmpty()) {
            filePath = "exported-ai-config.properties";
        }
        
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write("# AI服务配置文件 - 导出于 " + java.time.LocalDateTime.now() + "\n");
            writer.write("# AI Service Configuration File - Exported at " + java.time.LocalDateTime.now() + "\n\n");
            
            writer.write("# SiliconFlow API 配置\n");
            writer.write("siliconflow.api.key=" + config.getApiKey() + "\n");
            writer.write("siliconflow.api.base.url=" + config.getApiBaseUrl() + "\n");
            writer.write("siliconflow.api.timeout=" + config.getApiTimeout() + "\n");
            writer.write("siliconflow.api.retry.attempts=" + config.getApiRetryAttempts() + "\n\n");
            
            writer.write("# LLM模型配置\n");
            writer.write("llm.model.name=" + config.getLlmModelName() + "\n");
            writer.write("llm.model.max.tokens=" + config.getLlmMaxTokens() + "\n");
            writer.write("llm.model.temperature=" + config.getLlmTemperature() + "\n");
            writer.write("llm.model.top.p=" + config.getLlmTopP() + "\n\n");
            
            writer.write("# VLM模型配置\n");
            writer.write("vlm.model.name=" + config.getVlmModelName() + "\n");
            writer.write("vlm.model.max.tokens=" + config.getVlmMaxTokens() + "\n");
            writer.write("vlm.model.temperature=" + config.getVlmTemperature() + "\n");
            writer.write("vlm.model.top.p=" + config.getVlmTopP() + "\n\n");
            
            writer.write("# 处理配置\n");
            writer.write("processing.batch.size=" + config.getBatchSize() + "\n");
            writer.write("processing.max.concurrency=" + config.getMaxConcurrency() + "\n");
            writer.write("processing.timeout.seconds=" + config.getProcessingTimeout() + "\n");
            writer.write("processing.enable.cache=" + config.isCacheEnabled() + "\n");
            writer.write("processing.cache.ttl.minutes=" + config.getCacheTtlMinutes() + "\n\n");
            
            writer.write("# 质量控制配置\n");
            writer.write("quality.confidence.threshold=" + config.getQualityConfidenceThreshold() + "\n\n");
            
            writer.write("# 日志配置\n");
            writer.write("logging.level=" + config.getLogLevel() + "\n");
            writer.write("logging.enable.api.logs=" + config.isApiLogsEnabled() + "\n");
            writer.write("logging.enable.performance.logs=" + config.isPerformanceLogsEnabled() + "\n");
            
            System.out.println("✅ 配置已导出到: " + filePath);
            
        } catch (IOException e) {
            System.out.println("❌ 导出配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 重置为默认值
     */
    private void resetToDefaults() {
        System.out.println("\n🔄 重置为默认值");
        System.out.println("-".repeat(30));
        
        System.out.print("确认重置所有配置为默认值？ (y/N): ");
        String confirm = scanner.nextLine().trim().toLowerCase();
        
        if ("y".equals(confirm) || "yes".equals(confirm)) {
            config.clearOverrides();
            System.out.println("✅ 配置已重置为默认值");
        } else {
            System.out.println("❌ 重置操作已取消");
        }
    }
    
    /**
     * 掩码API密钥
     */
    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() <= 8) {
            return "****";
        }
        return apiKey.substring(0, 4) + "****" + apiKey.substring(apiKey.length() - 4);
    }
    
    /**
     * 主方法
     */
    public static void main(String[] args) {
        ConfigurationTool tool = new ConfigurationTool();
        tool.run();
    }
}